package appVersionRecord

import (
	"context"
	"crypto/md5"
	"encoding/hex"
	"errors"
	"github.com/google/uuid"
	"github.com/zeromicro/go-zero/core/logx"
	"insighttracking/apps/admin/internal/svc"
	"insighttracking/apps/admin/internal/types"
	"insighttracking/common/utils"
	"io"
	"net/http"
	"os"
)

type UploadFileApiLogic struct {
	logx.Logger
	ctx     context.Context
	svcCtx  *svc.ServiceContext
	Request *http.Request
}

func NewUploadFileApiLogic(ctx context.Context, svcCtx *svc.ServiceContext, request *http.Request) *UploadFileApiLogic {
	hostname, _ := os.Hostname()
	return &UploadFileApiLogic{
		Logger: logx.WithContext(ctx).WithCallerSkip(0).WithFields(
			logx.Field("Log_UUID", uuid.New().String()),
			logx.Field("hostname", hostname)),
		ctx:     ctx,
		svcCtx:  svcCtx,
		Request: request,
	}
}

func (l *UploadFileApiLogic) UploadFileApi() (resp *types.AppVersionRecordUploadFileResp, err error) {
	f, file, err := l.Request.FormFile("file")
	//fileType := path.Ext(file.Filename)

	fileName := file.Filename
	endpoint := l.svcCtx.Config.AliOssConfig.Endpoint
	accessKeyId := l.svcCtx.Config.AliOssConfig.AccessKeyID
	accessKeySecret := l.svcCtx.Config.AliOssConfig.AccessKeySecret
	bucketName := l.svcCtx.Config.AliOssConfig.BucketName
	bucketUrl := l.svcCtx.Config.AliOssConfig.BucketUrl
	fileOss := utils.NewRegisterOss(
		endpoint,
		accessKeyId,
		accessKeySecret,
		bucketName,
		bucketUrl,
		false,
		[]string{},
	)
	// 计算MD5哈希值
	hash := md5.New()
	if _, err := io.Copy(hash, f); err != nil {
		return nil, errors.New("上传失败1")
	}
	// 将哈希值转换为十六进制字符串
	md5Sum := hex.EncodeToString(hash.Sum(nil))
	uploadFile, err := fileOss.UploadFile("static/appVersion", true, file.Size, file)
	return &types.AppVersionRecordUploadFileResp{
		Url:  uploadFile,
		Name: fileName,
		Md5:  md5Sum,
	}, err
}
